package com.mall.domain.exception;

import com.mall.domain.Result;
import com.mall.domain.enums.BizCodeMessage;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 全局异常控制类
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 500异常处理
     */
    @ExceptionHandler(value = Exception.class)
    public Result errorHandler(HttpServletRequest request, Exception exception, HttpServletResponse response) {
        response.setStatus(HttpStatus.OK.value());
        response.setCharacterEncoding("UTF8");
        response.setHeader("Content-Type", "application/json");
        return Result.builder().code(BizCodeMessage.DEFAULT_ERROR.getcode()).message(BizCodeMessage.DEFAULT_ERROR.getMessage()).build();
    }

    /**
     * 500异常处理
     */
    @ExceptionHandler(value = BizException.class)
    public Result bizErrorHandler(HttpServletRequest request, BizException exception, HttpServletResponse response) {
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        response.setCharacterEncoding("UTF8");
        response.setHeader("Content-Type", "application/json");
        return Result.builder().code(exception.getCode()).message(exception.getMessage()).build();
//            response.getWriter().write(exception.getMessage());
    }

    /**
     * 500异常处理
     */
    @ExceptionHandler(value = OpenBizException.class)
    public Result openBizErrorHandler(HttpServletRequest request, OpenBizException exception, HttpServletResponse response) {
        response.setStatus(HttpStatus.OK.value());
        response.setCharacterEncoding("UTF8");
        response.setHeader("Content-Type", "application/json");
        return Result.builder().code(exception.getCode()).message(exception.getMessage()).build();
//            response.getWriter().write(exception.getMessage());
    }


}